/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */

package cc.iotkit.data.service;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.data.dao.DeviceGroupRepository;
import cc.iotkit.data.dao.DevicePartsRepository;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.manager.IDeviceGroupData;
import cc.iotkit.data.manager.IDevicePartsData;
import cc.iotkit.data.model.TbDeviceGroup;
import cc.iotkit.data.model.TbDeviceParts;
import cc.iotkit.data.model.TbSysConfig;
import cc.iotkit.data.model.TbSysMenu;
import cc.iotkit.data.util.PageBuilder;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.device.DeviceGroup;
import cc.iotkit.model.device.DeviceParts;
import cc.iotkit.model.system.SysConfig;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.List;

import static cc.iotkit.data.model.QTbBasMaintenanceUnit.tbBasMaintenanceUnit;
import static cc.iotkit.data.model.QTbDeviceParts.tbDeviceParts;
import static cc.iotkit.data.model.QTbSysMenu.tbSysMenu;

@Primary
@Service
public class DevicePartsDataImpl implements IDevicePartsData, IJPACommData<DeviceParts, Long> {
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private DevicePartsRepository devicePartsRepository;

    @Override
    public JpaRepository getBaseRepository() {
        return devicePartsRepository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbDeviceGroup.class;
    }

    @Override
    public Class getTClass() {
        return DeviceGroup.class;
    }



    @Override
    public DeviceParts findById(Long s) {
        return MapstructUtils.convert(devicePartsRepository.findById(s).orElse(null), DeviceParts.class);
    }

    @Override
    public DeviceParts save(DeviceParts data) {
        if (data.getId()==null||data.getId().equals(0L)) {
            data.setUid(LoginHelper.getUserId());
            data.setCreateAt(System.currentTimeMillis());
            data.setCreateBy(LoginHelper.getUserId());
        }else{
            data.setUpdateAt(System.currentTimeMillis());
            data.setUpdateBy(LoginHelper.getUserId());
        }
        devicePartsRepository.save(MapstructUtils.convert(data, TbDeviceParts.class));
        return data;
    }


    @Override
    public List<DeviceParts> findAll() {
        return MapstructUtils.convert(devicePartsRepository.findAll(), DeviceParts.class);
    }
    private Predicate buildPredicate(DeviceParts data) {
        return PredicateBuilder.instance()
                .and(StringUtils.isNotEmpty(data.getPartCode()), () -> tbDeviceParts.partCode.like("%"+data.getPartCode()+"%"))
                .and(StringUtils.isNotEmpty(data.getPartName()), () -> tbDeviceParts.partName.like("%"+data.getPartName()+"%"))
                .and(StringUtils.isNotEmpty(data.getPartModel()), () -> tbDeviceParts.partModel.like("%"+data.getPartModel()+"%"))
                .build();
    }
    public List<DeviceParts> findAllByCondition(DeviceParts query) {
        Predicate predicate = buildPredicate(query);
        List<DeviceParts> results = jpaQueryFactory.select(Projections.bean(DeviceParts.class,
                        tbDeviceParts.id,tbDeviceParts.remark,tbDeviceParts.partModel,
                        tbDeviceParts.partCode,tbDeviceParts.partName,tbDeviceParts.unitId,tbDeviceParts.uid,tbDeviceParts.maintenancePeriod,tbDeviceParts.createAt,tbDeviceParts.createDept,tbBasMaintenanceUnit.unitName))
                .from(tbDeviceParts)
                .leftJoin(tbBasMaintenanceUnit).on(tbBasMaintenanceUnit.id.eq(tbDeviceParts.unitId))
                .where(predicate).fetch();
        return results;

    }
    public Paging<DeviceParts> findAllByConditions(PageRequest<DeviceParts> pageRequest) {
        DeviceParts data = pageRequest.getData();
        Predicate predicate = buildPredicate(data);
        QueryResults<DeviceParts> results = jpaQueryFactory.select(Projections.bean(DeviceParts.class,
                        tbDeviceParts.id,tbDeviceParts.remark,tbDeviceParts.partModel,
                        tbDeviceParts.partCode,tbDeviceParts.partName,tbDeviceParts.unitId,tbDeviceParts.uid,tbDeviceParts.maintenancePeriod,tbDeviceParts.createAt,tbDeviceParts.createDept,tbBasMaintenanceUnit.unitName))
                .from(tbDeviceParts)
                .leftJoin(tbBasMaintenanceUnit).on(tbBasMaintenanceUnit.id.eq(tbDeviceParts.unitId))
                .where(predicate).limit(pageRequest.getPageSize()).offset(pageRequest.getOffset()).fetchResults();
        return new Paging<>(results.getTotal(), results.getResults());

    }
}
